package com.xxwy.dependency.scope;


import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.core.NamedThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义线程scope.
 *
 * @author xxwy
 * @date 2021/7/14 0014
 */
public class ThreadLocalDemo implements Scope {

    public static final String SCOPE_NAME = "thread-local";

    private final NamedThreadLocal<Map<String, Object>> threadLocal = new NamedThreadLocal<Map<String, Object>>("thread-local-scope"){
        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<>();
        }
    };

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Map<String, Object> objectMap = threadLocal.get();
        Object object = objectMap.get(name);
        if (object == null) {
            object = objectFactory.getObject();
           objectMap.put(name, object);
        }
        return object;
    }

    @Override
    public Object remove(String name) {
        return threadLocal.get().remove(name);
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
        // 销毁
    }


    @Override
    public Object resolveContextualObject(String key) {
        Map<String, Object> objectMap = threadLocal.get();
        return objectMap.get(key);
    }

    @Override
    public String getConversationId() {
        return String.valueOf(Thread.currentThread().getId());
    }
}
